import os
import subprocess
from multiprocessing import Process

dir = [x for x in os.listdir() if os.path.isdir(x)]
unruncases = []

threads = 16

for i in dir:
    os.chdir(i)
    cases = [x for x in os.listdir() if x[-3:] == '.js']
    for case in cases:
        if not os.path.exists(f'{case}.exitcode'):
            unruncases.append(f'{i}/{case}')
    os.chdir('..')


def run(caseList, threadNum):
    cases = [x for x in caseList if (
        caseList.index(x) + 1) % threads == threadNum]
    print(cases)
    for case in cases:
        print(f'Thread {i}: {cases.index(case)+1}/{len(cases)} {case}\n')
        proc = subprocess.run(['node', case], capture_output=True)
        with open(f'{case}.exitcode', 'w', encoding='utf-8') as f:
            f.write(str(proc.returncode))
        with open(f'{case}.out', 'w', encoding='utf-8') as f:
            f.writelines(proc.stdout.decode('utf-8'))
        with open(f'{case}.err', 'w', encoding='utf-8') as f:
            f.writelines(proc.stderr.decode('utf-8'))


plist = []
for i in range(threads):
    plist.append(Process(target=run, args=(unruncases, i)))
    plist[i].start()
